<template>
  <div>
    <el-upload
      v-model:file-list="fileList"
      action="#"
      list-type="picture-card"
      :auto-upload="false"
      :limit="1"
      :on-remove="handleRemove"
      :on-preview="handlePictureCardPreview"
    >
      <el-icon><Plus /></el-icon>
    </el-upload>

    <!-- 头像查看 -->
    <el-dialog 
      v-model="fileDialogVisible"
      width="50%"
    >
      <img 
        :src="dialogImageUrl" 
        alt="Preview Image"
        style="width: 100%; height: 100%;"
      />
    </el-dialog>
    <el-button 
      type="primary" 
      @click="uploadAvatar"
    >
      上传头像
    </el-button>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, inject, onMounted } from "vue";
// api
import editUserApi from "@/request/api/user";
// store
import useLoginStore from "@/store/login";
import { showMessageBox } from "@/utils/alertMsg";
import type { UploadUserFile, UploadFile  } from 'element-plus'

const loginStore = useLoginStore();
const props = defineProps({
  userInfo: {
    type: Object,
    default: () => ({}),
  }
});
// 刷新子路由
const reload: Function = inject("reload");

const fileList = ref<UploadUserFile[]>([])
const dialogImageUrl = ref<string>('')
const fileDialogVisible = ref<boolean>(false)

const OLD_ONE = 'old_avatar'
const init = () => {
  if (props.userInfo) {
    fileList.value.push({
      name: OLD_ONE,
      url: props.userInfo.avatar
    })
  }
}

onMounted(() => {
  init();
})

/**
 * defineEmits emit给父组件
 */
interface EmitEvent {
  (e: "closeDialog"): void;
}
const emit = defineEmits<EmitEvent>();
const close = () => {
  emit("closeDialog");
};


// 读取图像 获取源数据
function readImage(file: File) {
  const reader = new FileReader();
  let imageBinaryData: string | ArrayBuffer;
  reader.onload = function(e) {
    // 如果你需要获取原始图片的二进制数据，可以使用 reader.result
    imageBinaryData = reader.result;
    editUserApi.updateUserAvatar({
      avatar: imageBinaryData
    }).then((res: any) => {
      if (res.code == 200) {
        showMessageBox("success", res.msg, 3000, false);
        loginStore.getAndSetUserInfo();
        close();
        setTimeout(() => {
          reload();
        }, 500);
      } else {
        showMessageBox("error", res.msg, 3000, false);
      }
    })
  };
  reader.readAsDataURL(file);
}

const handlePictureCardPreview = (file: UploadFile) => {
  // console.log('file:', file)
  dialogImageUrl.value = file.url!
  fileDialogVisible.value = true
}

const handleRemove = (file: UploadFile) => {
  fileList.value.pop();
}

const uploadAvatar = () => {
  const firstChild = fileList.value[0];
  if(firstChild.name == OLD_ONE) {
    return showMessageBox('error', '请先更新头像再上传', 3000, false)
  }
  readImage(firstChild.raw)
}

// watch(() => fileList.value, (newVal) => {
//   // ruleForm.avatar = readImage(newVal[0].raw);
//   if(Object.entries(newVal).length === 0) {
//     ruleForm.avatar = ''
//   } else {
//     readImage(newVal[0].raw)
//   }
// }, { deep: true })
</script>

<style scoped lang="scss"></style>
